package hr.koshnica.android.service;

import hr.koshnica.android.database.KoshnicaContract.Locations;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import javax.ws.rs.core.UriBuilder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class DataFetchingService extends Service{

	private final IBinder dataServiceBinder;
	
	private final String TAG = "DATA SERVICE TAG";
	
	public DataFetchingService(){
		dataServiceBinder = new DataBinder();
	}
	
	@Override
	public void onCreate(){
		Log.i(TAG,
				"Creating Data Service**********************************************");
		
	}
	
	@Override
	public IBinder onBind(Intent intent){
		return dataServiceBinder;
	}
	
	public class DataBinder extends Binder{
		public DataFetchingService getDataFetchingService(){
			Log.i(TAG, "Returning the service");
			return DataFetchingService.this;
		}
	}
	/*
	private static URI getBaseURI() {
		return UriBuilder.fromUri("http://176.28.21.111:8080/KoshnicaService_v1.3").build();
	}*/
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId){
		
		try {

            
            URL url = new URL("http://176.28.21.111:8080/KoshnicaService_v1.3/rest/contacts/");
            Log.i(TAG, "url opend");
            URLConnection connection = url.openConnection();
            
            int responseCode = -1;
            HttpURLConnection httpConnection = null;
            int iRetry = 0;

            while (iRetry < 10) {
                iRetry++;
                try {
                    httpConnection = (HttpURLConnection) connection;
                    httpConnection.setConnectTimeout(3000);
                    httpConnection.setDoInput(true);
                    httpConnection.connect();
                    responseCode = httpConnection.getResponseCode();
                } catch (IOException e) {
                    e.printStackTrace();
                    responseCode = -1;
                }
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    iRetry = 10;
                    Log.i(TAG, "If it came to here web service is working");
                    InputStream in = httpConnection.getInputStream();                
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));
                    String jsonString = null;
                  
                    try {
                        // While the BufferedReader readLine is not null 
                        
                            jsonString = br.readLine();    
                        // Close the InputStream and BufferedReader
                            in.close();
                            br.close();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    
                    
                    Log.i(TAG,jsonString);
                    JSONObject jsonObject;

                    try {
                        jsonObject = new JSONObject(jsonString);    
                        JSONArray jsonArray = jsonObject.getJSONArray("contact");
                        for (int i = 0; i < jsonArray.length(); i++) {
       
                            JSONObject jsonContact = jsonArray.getJSONObject(i);
                            
                            JSONArray jArr2 = jsonContact.getJSONArray("address");
                            jsonObject = jArr2.getJSONObject(1);
                             
                            ContentValues values = new ContentValues();
                            values.put(Locations.LOC_NAME, jsonContact.getString("id"));
                            values.put(Locations.LOC_DESC, jsonContact.getString("name"));
                            values.put(Locations.LOC_GENRE, "mjuza");
                    		values.put(Locations.LOC_STATUS, "NEUTRAL");
                    		values.put(Locations.LOC_LIKE, 0);
                            Uri uri = Locations.CONTENT_URI;
                            getContentResolver().insert(uri, values);                          
                            
                        }
                        
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                   
                    Log.i(TAG, "doso do kraja!");
                    //addAllLocations(documentElement);
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
        }
		
		return Service.START_NOT_STICKY;
	}
		
		
}

